package com.eightbears.beboy.ui.user.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.UserPublishInfoListAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.entity.HomeListEntity;
import com.eightbears.beboy.entity.UserInfoEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.makeramen.roundedimageview.RoundedImageView;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_USER_ID;
import static com.eightbears.beboy.base.util.CommonAPI.URL_INVITATION;
import static com.eightbears.beboy.base.util.CommonAPI.URL_RESET_USERDATA;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.PostDetailActivity.EVENT_DELETE_POST;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_POST_ID;

public class UserPublishInfo extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener,
        SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.view_empty)
    View view_empty;

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;
    private String username;

    private UserInfoEntity userInfoEntity;
    private HomeListEntity.Post post;
    private HomeListEntity homeListEntity;
    private UserPublishInfoListAdapter userPublishInfoListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_publish_info);
        EventBus.getDefault().register(this);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        username = getIntent().getStringExtra(PARAMS_USER_ID);
        getUserInfo();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    private void initAdapter() {
        //下拉
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setProgressViewOffset(true, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        // adapter
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        userPublishInfoListAdapter = new UserPublishInfoListAdapter();
        userPublishInfoListAdapter.setOnLoadMoreListener(this);
        userPublishInfoListAdapter.addHeaderView(getHeadView());
        swipeLayout.setOnRefreshListener(this);
        rv_list.setAdapter(userPublishInfoListAdapter);
        userPublishInfoListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                post = (HomeListEntity.Post) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.rl_comment:
                        startLocalActivity(UserPublishInfo.this, PostDetailActivity.class, PARAMS_POST_ID, post.getId());
                        break;
                }
            }
        });
    }

    public View getHeadView() {
        View view = getLayoutInflater().inflate(R.layout.head_user_info, null);
        ImageView iv_head_bg = (ImageView) view.findViewById(R.id.iv_head_bg);
        ImageView iv_level = (ImageView) view.findViewById(R.id.iv_level);
        ImageView iv_vip = (ImageView) view.findViewById(R.id.iv_vip);
        RoundedImageView iv_head = (RoundedImageView) view.findViewById(R.id.iv_head);
        TextView tv_nickname = (TextView) view.findViewById(R.id.tv_nickname);

        if (null != userInfoEntity.getData().getCover()) {
            Glide.with(mContext).load(userInfoEntity.getData().getCover()).error(R.mipmap.default_head_image).into(iv_head_bg);
            Glide.with(mContext).load(userInfoEntity.getData().getCover()).error(R.mipmap.default_head).into(iv_head);
        }
        tv_nickname.setText(userInfoEntity.getData().getNickname());

        if (userInfoEntity.getData().getVip_level() == 1) {
            iv_vip.setVisibility(View.VISIBLE);
            iv_vip.setImageResource(R.mipmap.icon_new_vip1);
        } else if (userInfoEntity.getData().getVip_level() == 2) {
            iv_vip.setVisibility(View.VISIBLE);
            iv_vip.setImageResource(R.mipmap.icon_new_vip2);
        } else {
            iv_vip.setVisibility(View.GONE);
        }

        if (userInfoEntity.getData().getPoints() != null) {
            if (userInfoEntity.getData().getPoints().getLevel() == 1) {
                iv_level.setImageResource(R.mipmap.icon_level_one);
            } else if (userInfoEntity.getData().getPoints().getLevel() == 2) {
                iv_level.setImageResource(R.mipmap.icon_level_two);
            } else if (userInfoEntity.getData().getVip_level() == 3) {
                iv_level.setImageResource(R.mipmap.icon_level_three);
            } else if (userInfoEntity.getData().getVip_level() == 4) {
                iv_level.setImageResource(R.mipmap.icon_level_four);
            } else if (userInfoEntity.getData().getVip_level() == 5) {
                iv_level.setImageResource(R.mipmap.icon_level_five);
            }
            iv_level.setVisibility(View.VISIBLE);
        }
        return view;
    }

    /**
     * 获取用户数据
     */
    public void getUserInfo() {
        OkHttpUtils.get().url(URL_RESET_USERDATA + username)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                userInfoEntity = GsonUtil.fromJson(response, UserInfoEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(userInfoEntity.getStatus_code())) {
                    initAdapter();
                    getData();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(UserPublishInfo.this, status_error);
            }
        });
    }

    /**
     * 获取列表信息
     */
    private void getData() {
        swipeLayout.setRefreshing(true);
        OkHttpUtils.get().url(URL_INVITATION)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", String.valueOf(page))
                .addParams("size", String.valueOf(PARAMS_PAGE_SIZE))
                .addParams("type", "7")
                .addParams("user_id", username)
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                homeListEntity = GsonUtil.fromJson(response, HomeListEntity.class);
                if (CONNECTION_STATUS_SUCCESS.equals(homeListEntity.getStatus_code())) {
                    isEnd = homeListEntity.getData().getIs_end();
                    classifyItem();
                    if (page == 1) {
                        if (homeListEntity.getData().getList().size() > 0) {
                            view_empty.setVisibility(View.GONE);
                        }
                        userPublishInfoListAdapter.setNewData(homeListEntity.getData().getList());
                    } else {
                        userPublishInfoListAdapter.addData(homeListEntity.getData().getList());
                        userPublishInfoListAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(UserPublishInfo.this, status_error);
            }
        });
    }

    String tempDate;

    private void classifyItem() {
        List<HomeListEntity.Post> temp = homeListEntity.getData().getList();
        if (temp.size() != 0) {
            for (int i = 0; i < homeListEntity.getData().getList().size(); i++) {
                HomeListEntity.Post tempPost = homeListEntity.getData().getList().get(i);
                if (TextUtils.isEmpty(tempDate)) {
                    tempDate = CommonUtils.TimeStamp2Date(tempPost.getCreated_at(), "MM-dd");
                    tempPost.setHeadTitle(true);
                }

                if (!tempDate.equals(CommonUtils.TimeStamp2Date(tempPost.getCreated_at(), "MM-dd"))) {
                    tempDate = CommonUtils.TimeStamp2Date(tempPost.getCreated_at(), "MM-dd");
                    tempPost.setHeadTitle(true);
                }
            }
        }
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @Override
    public void onRefresh() {
        userPublishInfoListAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                userPublishInfoListAdapter.getData().clear();
                getData();
                userPublishInfoListAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    userPublishInfoListAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(UserPublishInfo.this, R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        userPublishInfoListAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_DELETE_POST:
                userPublishInfoListAdapter.getData().remove(post);
                userPublishInfoListAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
